package com.eltsistemas.controller.setor;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.eltsistemas.dao.GenericDao;
import com.eltsistemas.hibernate.HibernateUtil;
import com.eltsistemas.modelo.Responsavel;
import com.eltsistemas.modelo.Setor;

@Controller
@RequestMapping(value="/setor")
public class SetorAltera {
	
	@RequestMapping(value="/alterado", method=RequestMethod.POST)
	public String altera(Setor setor, Long idResponsavel)
	{
		try
		{
			Session session = new HibernateUtil().getSession();
			session.beginTransaction();
					
			GenericDao<Setor> daoSetor = new GenericDao<>(session, Setor.class);
			if( daoSetor.findByName_ForUpdate(setor.getNome(), setor.getId()) == null)
			{
				Responsavel responsavel = (Responsavel) session.load(Responsavel.class, idResponsavel);
				setor.setResponsavel(responsavel);
				
				//Comita os dados
				session = daoSetor.altera(setor);
				session.beginTransaction().commit();
				session.close();
				return "redirect:lista";
			}
			else
			{
				session.close();
				return "redirect:lista?valor=existe";
			}
		}
		catch(HibernateException e)
		{
			return "redirect:/painel/erro";
		}
	}

}
